<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *  This file is part of CI-ActiveRecord
 *
 *  CI-ActiveRecord is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  CI-ActiveRecord is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with CI-ActiveRecord.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * ActiveRecord_Behaviour_Encrypted
 */
class ActiveRecord_Behaviour_Encrypted extends ActiveRecord_Behaviour {

    /**
     * Array of encryption options
     */
    protected $_options = array('fields' =>  array('password'=>'SHA1'));

    /**
     * __construct
     * 
     * @param object $invoker Instance of ActiveRecord
     * @param array $options array of encryption options 
     */
    public function __construct(ActiveRecord $invoker, array $options=array())
    {
        parent::__construct($invoker, $options);
        $this->getInvoker()->addListener(new ActiveRecord_Listener_Encrypted($this->_options));
    }
}

/**
 * ActiveRecord_Listener_Encrypted
 */
class ActiveRecord_Listener_Encrypted extends ActiveRecord_Listener {
    
    /**
     * Array of encryption options
     */
    protected $_options = array();
    
    /**
     * __construct
     *
     * @param string $options 
     * @return void
     */
    public function __construct(array $options)
    {
        $this->_options = $options;
    }
    
    public function preSave(ActiveRecord_Event $event)
    {
        foreach ($this->_options['fields'] as $field => $type) {
            switch ($type) {
                case 'SHA1':
                    $encypted = sha1($event->getInvoker()->$field);
                    break;
                case 'MD5':
                    $encypted = md5($event->getInvoker()->$field);
                    break;
                default:
                    log_message('error', "Unknown encryption type '$type'.");
            }
            $event->getInvoker()->$field = $encypted;
        }
    }
}